<template>
    <div ref="pieChart" style="width: 350px; height: 350px;"></div>
  </template>
  
  <script>
    import * as echarts from 'echarts';
  
  export default {
    name: 'PieChart',
    props: {
      chartData: {
        type: Array,
        required: true,
      },
    },
    data() {
      return {
        chartInstance: null,
      };
    },
    mounted() {
      this.initChart();
      window.addEventListener('resize', this.handleResize);
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.handleResize);
      if (this.chartInstance) {
        this.chartInstance.dispose();
      }
    },
    methods: {
      initChart() {
        this.chartInstance = echarts.init(this.$refs.pieChart);
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)',
          },
          legend: {
            orient: 'vertical',
            left: 'left',
          },
          series: [
            {
              name: '数据统计',
              type: 'pie',
              radius: '50%',
              data: this.chartData,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)',
                },
              },
            },
          ],
        };
        this.chartInstance.setOption(option);
      },
      handleResize() {
        if (this.chartInstance) {
          this.chartInstance.resize();
        }
      },
    },
    watch: {
      // 监听数据变化，重新渲染图表
      chartData: {
        handler() {
          if (this.chartInstance) {
            this.chartInstance.setOption({
              series: [{ data: this.chartData }],
            });
          }
        },
        deep: true,
      },
    },
  };
  </script>